<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\AdminLoginRequest;
use App\Model\Admin\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    protected $guard = 'admin';

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * 显示登陆界面
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showLogin()
    {
        return view('admin.login');
    }

    public function login(AdminLoginRequest $request)
    {
        $data = $request->all();

        $user = User::where('name',$data['name'])->first();

        if (empty($user)){
            return ['code' => 1 ,'msg'=>'没有找到该用户'];
        }

        if (!password_verify($data['password'], $user->password)){
            return ['code' => 2 ,'msg'=>'用户名或者密码不正确'];
        }

        session(['user' => $user->toArray()]);
        return ['code' => 0, 'msg' => '登录成功','redirect' => true];
    }

    public function guard()
    {
        return \Auth::guard($this->guard);
    }

    public function username()
    {
        return 'name';
    }
}
